<?php

namespace App\Http\Controllers;

use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Firebase\JWT\JWT;

class AuthController extends Controller
{
    /**
     * 微信登录
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',
            'nickname' => 'required',
            'avatar' => 'required'
        ]);

        $code = $request->input('code');
        $nickname = $request->input('nickname');
        $avatar = $request->input('avatar');

        // 调用微信API获取openid
        $client = new Client();
        $response = $client->get('https://api.weixin.qq.com/sns/jscode2session', [
            'query' => [
                'appid' => env('WECHAT_APPID'),
                'secret' => env('WECHAT_SECRET'),
                'js_code' => $code,
                'grant_type' => 'authorization_code'
            ]
        ]);

        $data = json_decode($response->getBody(), true);
        
        if (isset($data['errcode'])) {
            return response()->json([
                'code' => 400,
                'message' => '登录失败: ' . $data['errmsg']
            ]);
        }

        $openid = $data['openid'];
        $sessionKey = $data['session_key'];

        // 查找或创建用户
        $user = User::where('openid', $openid)->first();
        
        if (!$user) {
            $user = new User();
            $user->openid = $openid;
            $user->nickname = $nickname;
            $user->avatar = $avatar;
            $user->create_time = time();
        } else {
            // 更新用户信息
            $user->nickname = $nickname;
            $user->avatar = $avatar;
            $user->last_login_time = time();
        }
        
        $user->save();

        // 生成JWT token
        $token = JWT::encode(
            [
                'sub' => $user->id,
                'iat' => time(),
                'exp' => time() + 7 * 24 * 60 * 60
            ],
            env('APP_KEY', 'default-key'),
            'HS256'
        );

        return response()->json([
            'code' => 200,
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $user->id,
                    'nickname' => $user->nickname,
                    'avatar' => $user->avatar,
                    'total_score' => $user->total_score,
                    'win_count' => $user->win_count,
                    'lose_count' => $user->lose_count
                ]
            ],
            'message' => '登录成功'
        ]);
    }
}